package net.lzzy.practicesapi1.services;

import net.lzzy.practicesapi1.entities.User;
import net.lzzy.practicesapi1.repositories.UserProjection;
import net.lzzy.practicesapi1.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Administrator
 * 1.字段注入，最简单，不像其他两种可穿递参数，无法保证依赖的完全性
 * 2.setter注入，时机灵活，可在对象创建时注入，适用于要注入的对象可能用到、也可能用不到，有可能出现NullPointerExceptoin
 * 3.构造器注入，时机最早，保证对象有值（repository为不可变对象，所以final修饰）
 */
@Service
public class UserServiceImpl implements UserService {
    private final UserRepository repository;
    @Autowired
    public UserServiceImpl(UserRepository repository) {
        this.repository = repository;
    }

    @Override
    public User check(String userName, String password) {
        return repository.findUserByUserNameAndPassword(userName,password);
    }

    @Override
    public boolean isUserNameOccupied(String userName) {
        return repository.countByUserName(userName) > 0;
    }

    @Override
    public User register(User user) {
        return repository.save(user);
    }

    @Override
    public String getSalt(String userName) {
        UserProjection projection = repository.findUserByUserName(userName);
        if(projection == null){
            return"";
        }
        return projection.getSalt();
    }
}
